package com.qifan.energy.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qifan.energy.base.BaseActivity;
import com.qifan.energy.bean.result.AddressItem;
import com.qifan.energy.bean.vo.AddressAddVO;
import com.qifan.energy.mvp.callback.IEventCallback;
import com.qifan.energy.R;
import com.qifan.energy.adapter.AddressListAdapter;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.Values;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.IntentUtils;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.widget.dialog.LoadingUtils;
import com.qifan.energy.widget.dialog.NormalCenterDialog;
import com.orhanobut.logger.Logger;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class AddressListActivity extends BaseActivity {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private List<AddressItem> dataList = new ArrayList();
    private AddressListAdapter adapter;
    private int orderType = 0;//默认是从我的地址跳转过来的 0

    /*@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_list);
    }*/

    @Override
    protected int getLayoutId() {
        return R.layout.activity_address_list;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        /* 更改状态栏 */
        changeStatusTransparentFontBlack();

        orderType = getIntent().getIntExtra(Keys.ADRESS_ORDER_TYPE,0);

        /* 适配器设置 */
        adapter = new AddressListAdapter(dataList);
        adapter.setOnItemClickListener((a,v,p) -> {
            if (orderType == 1){
                final AddressItem item = (AddressItem)a.getData().get(p);
                Intent intent = new Intent();
                intent.putExtra(Keys.FROM_ORDER_KEY, item);
                setResult(RESULT_OK,intent);
                //跳转
                ActivityStackUtil.finishTopActivity();
            }
        });
        /* 监听子控件点击 */
        adapter.setOnItemChildClickListener(this::onItemChildClick);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .sizeResId(R.dimen.dp_5)
                .colorResId(R.color.divider_color)
                .build());
        //添加空布局
        adapter.setEmptyView(getEmptyDataView());
    }

    @Override
    protected void initData() {
        memberAddressList();
    }

    private void onItemChildClick(BaseQuickAdapter a, View v, int p) {
        final AddressItem item = (AddressItem)a.getData().get(p);
        switch (v.getId()) {
            case R.id.default_address_tv:
                memberAddressUpdate(item);
                break;
            case R.id.edit_tv:
                Intent intent = new Intent();
                intent.putExtra(Keys.UPDATE_ADDRESS_KEY, item);
                IntentUtils.startActivityForResult(this,AddressUpdateActivity.class, intent,Values.REQUEST_CODE_1);
                break;
            case R.id.delete_tv:
                new NormalCenterDialog().showNow2(getSupportFragmentManager(),"delete").title("确定删除此地址吗？").setEventCallback(new IEventCallback() {
                    @Override
                    public void onCancel() {
                        Logger.i("点击取消");
                    }
                    @Override
                    public void onComfirm() {
                        memberAddressDelete(item.getId());
                    }
                });
                break;
            default:
                break;
        }
    }

    /* 修改默认地址接口 */
    private void memberAddressUpdate(AddressItem item){
        if (item.getDefaultStatus() == 0){//未选中
            NetUtils.memberAddressUpdateDefaultAddress(item.getId(), new MyObserver<String>(this) {
                @Override
                public void onSuccess(String result) {
                    item.setDefaultStatus(1);
                    ToastUtils.showShort("已选择默认地址");
                    /* 重新获取列表数据 */
                    memberAddressList();
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    ToastUtils.showShort(errorMsg);
                }
            });
        } else {
            AddressAddVO addressAddVO = new AddressAddVO();
            addressAddVO.setProvince(item.getProvince());
            addressAddVO.setCity(item.getCity());
            addressAddVO.setRegion(item.getRegion());
            addressAddVO.setName(item.getName());
            addressAddVO.setPhoneNumber(item.getPhoneNumber());
            addressAddVO.setDetailAddress(item.getDetailAddress());
            addressAddVO.setMemberId(item.getMemberId());
            int status = (item.getDefaultStatus() == 0 ? 1:0);
            addressAddVO.setDefaultStatus(status);
            NetUtils.memberAddressUpdate(item.getId(),addressAddVO,new MyObserver<String>(this) {
                @Override
                public void onSuccess(String result) {
                    item.setDefaultStatus(status);
                    /* 提示并刷新 */
                    if (status == 0){
                        ToastUtils.showShort("已取消默认地址");
                    } else {
                        ToastUtils.showShort("已选择默认地址");
                        /* 重新获取列表数据 */
                        memberAddressList();
                    }
                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    ToastUtils.showShort(errorMsg);
                }
            });
        }
    }

    /* 地址列表接口 */
    private void memberAddressList(){
        LoadingUtils.show(this);
        NetUtils.memberAddressList(new MyObserver<List<AddressItem>>(this) {
            @Override
            public void onSuccess(List<AddressItem> result) {
                LoadingUtils.hide();
                if (null != result){
                    dataList = result;
                    adapter.setNewData(result);
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LoadingUtils.hide();
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 删除收货地址 */
    private void memberAddressDelete(Integer id){
        NetUtils.memberAddressDelete(id ,new MyObserver<String>(this) {
            @Override
            public void onSuccess(String result) {
                ToastUtils.showShort("删除成功!");
                /* 重新获取 */
                memberAddressList();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                ToastUtils.showShort(errorMsg);
            }
        });
    }

    /* 获取空布局 */
    private View getEmptyDataView() {
        return getLayoutInflater().inflate(R.layout.address_list_empty, recyclerView, false);
    }

    @OnClick(R.id.add_address_tv)
    void onAddAddressTvClicked(){
        IntentUtils.startActivityForResult(this,AddressUpdateActivity.class,Values.REQUEST_CODE_1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK){
            switch (requestCode) {
                case Values.REQUEST_CODE_1:
                    memberAddressList();
                    break;
            }
        }
    }
}
